package com.dashan.backend.datastore;

import java.util.Date;
import java.util.List;

import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;


public class StatusHistoryDao extends DaoBase {
    
    @SuppressWarnings("unchecked")
    public List<DsStatus> getStatusHistory(String userName) {
        Query query = pm.newQuery(DsStatus.class);
        query.setFilter(String.format("userName == \"%s\"",userName));
        query.setOrdering("timestamp desc");
        return (List<DsStatus>) query.execute();
    }
    
    @SuppressWarnings("unchecked")
    public List<DsStatus> getStatusHistory(String userName, int count) {
        Query query = pm.newQuery(DsStatus.class);
        query.setFilter(String.format("userName == \"%s\"",userName));
        query.setOrdering("timestamp desc");
        query.setRange(0, count);
        return (List<DsStatus>) query.execute();
    }
    
    @SuppressWarnings("unchecked")
    public List<DsStatus> getStatusHistory(String userName, Date from, Date to) {
        Query query = pm.newQuery(DsStatus.class);
        query.setFilter(String.format("userName == \"%s\" && ",userName) + 
                "timestamp >= fromParam && timestamp <= toParam");
        query.declareImports("import java.util.Date");
        query.declareParameters("Date fromParam, Date toParam");
        query.setOrdering("timestamp desc");

        return (List<DsStatus>) query.execute(from, to);
    }
    
    public void addStatus(DsStatus status) {
        pm.makePersistent(status);
    }
    
    public DsStatus getStatusByKey(Key key) {
        return (DsStatus) pm.getObjectById(DsStatus.class, key);
    }
}
